'use client'

import { useState, useEffect } from 'react'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'
import { useToast } from '@/hooks/use-toast'
import { User, Lock, Mail, Calendar, HardDrive } from 'lucide-react'
import { Progress } from '@/components/ui/progress'

export default function UserProfilePage() {
  const { toast } = useToast()
  const [user, setUser] = useState<any>(null)
  const [isEditing, setIsEditing] = useState(false)
  const [isChangingPassword, setIsChangingPassword] = useState(false)
  const [formData, setFormData] = useState({
    email: '',
    name: ''
  })
  const [passwordData, setPasswordData] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  const [stats, setStats] = useState({
    ai_count: 0,
    ai_count_limit: 0,
    copy_count: 0,
    copy_count_limit: 0,
    script_count: 0,
    script_count_limit: 0,
    topic_count: 0,
    topic_count_limit: 0,
    voice_count: 0,
    voice_count_limit: 0,
    subtitle_count: 0,
    subtitle_count_limit: 0
  })
  
  // 新增存储信息状态
  const [storageInfo, setStorageInfo] = useState({
    storageUsed: 0,
    storageLimit: 100,
    usagePercentage: 0,
    remainingMB: 100,
    planType: 'free'
  })

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        const response = await fetch('/api/auth/me', {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        const userData = await response.json()
        setUser(userData)
        setFormData({
          email: userData.email || '',
          name: userData.name || ''
        })
        setStats({
          ai_count: userData.ai_count || 0,
          ai_count_limit: userData.ai_count_limit || 0,
          copy_count: userData.copy_count || 0,
          copy_count_limit: userData.copy_count_limit || 0,
          script_count: userData.script_count || 0,
          script_count_limit: userData.script_count_limit || 0,
          topic_count: userData.topic_count || 0,
          topic_count_limit: userData.topic_count_limit || 0,
          voice_count: userData.voice_count || 0,
          voice_count_limit: userData.voice_count_limit || 0,
          subtitle_count: userData.subtitle_count || 0,
          subtitle_count_limit: userData.subtitle_count_limit || 0
        })
      } catch (error) {
        console.error('Failed to fetch user data:', error)
        toast({
          title: "错误",
          description: "获取用户信息失败",
          variant: "destructive"
        })
      }
    }

    // 新增获取存储信息的函数
    const fetchStorageInfo = async () => {
      try {
        const response = await fetch('/api/user/storage', {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        if (response.ok) {
          const data = await response.json()
          setStorageInfo(data)
        }
      } catch (error) {
        console.error('Failed to fetch storage info:', error)
      }
    }

    fetchUserData()
    fetchStorageInfo()
  }, [])

  const [isUpdating, setIsUpdating] = useState(false)

  const handleUpdateProfile = async () => {
    if (isUpdating) return // 防止重复提交
    
    setIsUpdating(true)
    try {
      const response = await fetch('/api/user/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({ name: formData.name }) // 只发送name字段
      })
  
      if (response.ok) {
        const updatedUser = await response.json()
        // 同时更新user状态和formData状态
        setUser(updatedUser)
        setFormData({
          email: updatedUser.email || '',
          name: updatedUser.name || ''
        })
        // 更新统计数据
        setStats({
          ai_count: updatedUser.ai_count || 0,
          ai_count_limit: updatedUser.ai_count_limit || 0,
          copy_count: updatedUser.copy_count || 0,
          copy_count_limit: updatedUser.copy_count_limit || 0,
          script_count: updatedUser.script_count || 0,
          script_count_limit: updatedUser.script_count_limit || 0,
          topic_count: updatedUser.topic_count || 0,
          topic_count_limit: updatedUser.topic_count_limit || 0,
          voice_count: updatedUser.voice_count || 0,
          voice_count_limit: updatedUser.voice_count_limit || 0,
          subtitle_count: updatedUser.subtitle_count || 0,
          subtitle_count_limit: updatedUser.subtitle_count_limit || 0
        })
        setIsEditing(false)
        toast({
          title: "成功",
          description: "个人信息更新成功"
        })
      } else {
        const errorData = await response.json()
        throw new Error(errorData.error || '更新失败')
      }
    } catch (error: any) {
      console.error('Update profile error:', error)
      toast({
        title: "错误",
        description: error.message || "更新个人信息失败",
        variant: "destructive"
      })
    } finally {
      setIsUpdating(false)
    }
  }

  const handleChangePassword = async () => {
    if (passwordData.newPassword !== passwordData.confirmPassword) {
      toast({
        title: "错误",
        description: "新密码和确认密码不匹配",
        variant: "destructive"
      })
      return
    }

    if (passwordData.newPassword.length < 6) {
      toast({
        title: "错误",
        description: "新密码长度至少为6位",
        variant: "destructive"
      })
      return
    }

    try {
      const response = await fetch('/api/user/password', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({
          currentPassword: passwordData.currentPassword,
          newPassword: passwordData.newPassword
        })
      })

      if (response.ok) {
        setIsChangingPassword(false)
        setPasswordData({ currentPassword: '', newPassword: '', confirmPassword: '' })
        toast({
          title: "成功",
          description: "密码修改成功"
        })
      } else {
        const error = await response.json()
        throw new Error(error.message || '密码修改失败')
      }
    } catch (error: any) {
      toast({
        title: "错误",
        description: error.message || "密码修改失败",
        variant: "destructive"
      })
    }
  }

  if (!user) {
    return (
      <div className="container mx-auto py-8 px-4">
        <div className="text-center">加载中...</div>
      </div>
    )
  }

  return (
    <div className="container mx-auto py-8 px-4 max-w-4xl">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">个人中心</h1>
        <p className="text-gray-600">管理您的账户信息和使用情况</p>
      </div>

      {/* 个人信息卡片 */}
      <Card className="mb-8">
        <CardHeader className="flex flex-row items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-gradient-to-br from-rose-500 to-purple-500 rounded-full flex items-center justify-center">
              <User className="w-6 h-6 text-white" />
            </div>
            <div>
              <CardTitle>个人信息</CardTitle>
              <p className="text-sm text-gray-600">管理您的基本信息</p>
            </div>
          </div>
          <Button 
            variant={isEditing ? "outline" : "default"}
            onClick={() => {
              if (isEditing) {
                setFormData({
                  email: user.email || '',
                  name: user.name || ''
                })
              }
              setIsEditing(!isEditing)
            }}
          >
            {isEditing ? '取消' : '编辑'}
          </Button>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="email">邮箱地址</Label>
              <div className="flex items-center gap-2 mt-1">
                <Mail className="w-4 h-4 text-gray-400" />
                <Input
                  id="email"
                  type="email"
                  value={formData.email}
                  disabled={true}
                  className="bg-gray-50 cursor-not-allowed"
                  title="邮箱地址不可修改"
                />
              </div>
            </div>
            <div>
              <Label htmlFor="name">用户名</Label>
              <div className="flex items-center gap-2 mt-1">
                <User className="w-4 h-4 text-gray-400" />
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  disabled={!isEditing}
                  placeholder="请输入用户名"
                  className={!isEditing ? "bg-gray-50" : ""}
                />
              </div>
            </div>
          </div>
         
          {isEditing && (
            <div className="flex gap-2 pt-4">
              <Button onClick={handleUpdateProfile}>保存更改</Button>
              <Button 
                variant="outline" 
                onClick={() => {
                  setFormData({
                    email: user.email || '',
                    name: user.name || ''
                  })
                  setIsEditing(false)
                }}
              >
                取消
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 密码修改卡片 */}
      <Card className="mb-8">
        <CardHeader className="flex flex-row items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-indigo-500 rounded-full flex items-center justify-center">
              <Lock className="w-6 h-6 text-white" />
            </div>
            <div>
              <CardTitle>密码安全</CardTitle>
              <p className="text-sm text-gray-600">修改您的登录密码</p>
            </div>
          </div>
          <Button 
            variant={isChangingPassword ? "outline" : "default"}
            onClick={() => {
              if (isChangingPassword) {
                setPasswordData({ currentPassword: '', newPassword: '', confirmPassword: '' })
              }
              setIsChangingPassword(!isChangingPassword)
            }}
          >
            {isChangingPassword ? '取消' : '修改密码'}
          </Button>
        </CardHeader>
        {isChangingPassword && (
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="currentPassword">当前密码</Label>
              <Input
                id="currentPassword"
                type="password"
                value={passwordData.currentPassword}
                onChange={(e) => setPasswordData({ ...passwordData, currentPassword: e.target.value })}
                placeholder="请输入当前密码"
              />
            </div>
            <div>
              <Label htmlFor="newPassword">新密码</Label>
              <Input
                id="newPassword"
                type="password"
                value={passwordData.newPassword}
                onChange={(e) => setPasswordData({ ...passwordData, newPassword: e.target.value })}
                placeholder="请输入新密码（至少6位）"
              />
            </div>
            <div>
              <Label htmlFor="confirmPassword">确认新密码</Label>
              <Input
                id="confirmPassword"
                type="password"
                value={passwordData.confirmPassword}
                onChange={(e) => setPasswordData({ ...passwordData, confirmPassword: e.target.value })}
                placeholder="请再次输入新密码"
              />
            </div>
            <div className="flex gap-2 pt-4">
              <Button onClick={handleChangePassword}>确认修改</Button>
              <Button 
                variant="outline" 
                onClick={() => {
                  setPasswordData({ currentPassword: '', newPassword: '', confirmPassword: '' })
                  setIsChangingPassword(false)
                }}
              >
                取消
              </Button>
            </div>
          </CardContent>
        )}
      </Card>

      {/* 存储使用情况卡片 */}
      <Card className="mb-8">
        <CardHeader>
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-gradient-to-br from-cyan-500 to-blue-500 rounded-full flex items-center justify-center">
              <HardDrive className="w-6 h-6 text-white" />
            </div>
            <div>
              <CardTitle>存储使用情况</CardTitle>
              <p className="text-sm text-gray-600">查看您的文件存储使用情况</p>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium">已使用存储空间</span>
              <span className="text-sm text-gray-600">
                {storageInfo.storageUsed}MB / {storageInfo.storageLimit === -1 ? '无限制' : `${storageInfo.storageLimit}MB`}
              </span>
            </div>
            
            {storageInfo.storageLimit !== -1 && (
              <>
                <Progress 
                  value={storageInfo.usagePercentage} 
                  className="w-full h-2"
                />
                <div className="flex justify-between text-xs text-gray-500">
                  <span>使用率: {storageInfo.usagePercentage}%</span>
                  <span>剩余: {storageInfo.remainingMB}MB</span>
                </div>
              </>
            )}
            
            <div className="flex items-center justify-between pt-2 border-t">
              <span className="text-sm font-medium">当前套餐</span>
              <span className="text-sm px-2 py-1 bg-blue-100 text-blue-800 rounded-full capitalize">
                {storageInfo.planType}
              </span>
            </div>
            
            {storageInfo.usagePercentage > 80 && storageInfo.storageLimit !== -1 && (
              <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 bg-yellow-500 rounded-full flex-shrink-0"></div>
                  <p className="text-sm text-yellow-800">
                    存储空间即将用完，建议清理不需要的文件或升级套餐
                  </p>
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 使用统计 */}
      <Card>
        <CardHeader>
          <CardTitle>使用统计</CardTitle>
          <p className="text-sm text-gray-600">查看您的平台使用情况</p>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
            <div className="text-center p-4 bg-gradient-to-br from-blue-50 to-indigo-50 rounded-lg">
              <div className="text-2xl font-bold text-blue-600">{stats.topic_count}</div>
              <div className="text-sm text-gray-600">项目数量</div>
              <div className="text-xs text-gray-500">限制: {stats.topic_count_limit}</div>
            </div>
            <div className="text-center p-4 bg-gradient-to-br from-green-50 to-emerald-50 rounded-lg">
              <div className="text-2xl font-bold text-green-600">{stats.copy_count}</div>
              <div className="text-sm text-gray-600">文案数量</div>
              <div className="text-xs text-gray-500">限制: {stats.copy_count_limit}</div>
            </div>
            <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-violet-50 rounded-lg">
              <div className="text-2xl font-bold text-purple-600">{stats.ai_count}</div>
              <div className="text-sm text-gray-600">AI使用次数</div>
              <div className="text-xs text-gray-500">限制: {stats.ai_count_limit}</div>
            </div>
            <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-red-50 rounded-lg">
              <div className="text-2xl font-bold text-orange-600">{stats.voice_count}</div>
              <div className="text-sm text-gray-600">语音合成</div>
              <div className="text-xs text-gray-500">限制: {stats.voice_count_limit}</div>
            </div>
            <div className="text-center p-4 bg-gradient-to-br from-pink-50 to-rose-50 rounded-lg">
              <div className="text-2xl font-bold text-pink-600">{stats.subtitle_count}</div>
              <div className="text-sm text-gray-600">字幕生成</div>
              <div className="text-xs text-gray-500">限制: {stats.subtitle_count_limit}</div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
